const { data, userList } = require('../mock')
const bodyParser = require('body-parser')
const jwt = require('jsonwebtoken')


// 购物车数据
let shopCar = []

const isVerify = (req, res, success) => {
    const { authorization } = req.headers

    try {
        jwt.verify(authorization, '1906A')

        success()
    } catch {
        res.status(401).send({
            code: 0,
            msg: '无权限'
        })
    }
}


module.exports = app => {
    app.use(bodyParser.json())

    app.post('/api/getList', (req, res) => {
        let { key, page } = req.body

        isVerify(req, res, () => {
            // 如果解密成功

            // 通过type类型赛选
            const newData = data.filter(item => item.type === key * 1)

            res.send({
                code: 1,
                total: newData.length,
                data: newData.filter((item, idx) => idx < page * 10) // 通过分页器赛选
            })
        })



    })

    app.post('/api/getDetail', (req, res) => {
        const { id } = req.body

        // 添加鉴权校验
        isVerify(req, res, () => {
            res.send({
                code: 1,
                data: data.find(item => item.id === id)
            })
        })
    })

    app.post('/api/addShopCar', (req, res) => {
        const {
            id,
            img,
            title,
            type,
            price,
            number
        } = req.body

        if (shopCar.some(item => item.id === id)) {
            shopCar = shopCar.map(item => {
                if (item.id === id) {
                    return {
                        ...item,
                        number: item.number + number
                    }
                } else return item

            })
        } else {
            shopCar.push({
                id,
                img,
                title,
                type,
                price,
                number
            })
        }

        res.send({
            code: 1,
            msg: '添加成功'
        })


    })

    app.post('/api/getShopCar', (req, res) => {
        res.send({
            code: 1,
            data: shopCar
        })
    })

    app.post('/api/login', (req, res) => {
        const {
            username,
            password
        } = req.body

        if (userList.some(item => item.username === username && item.password === password)) {
            const token = jwt.sign(username, '1906A')

            res.send({
                code: 1,
                token
            })
        }
    })
}



